
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

public class RadBag {

    public static void main(String[] args) {
        JFrame frame = new JFrame("拆红包");
        frame.setBounds(400, 300, 400, 300);
        frame.setResizable(true);

        JPanel contentPane = new JPanel();
        frame.setContentPane(contentPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        // contentPane.setLayout(null);

        JLabel lblBag = new JLabel();
        Icon icon = new ImageIcon(RadBag.class.getResource("1.png"));
        lblBag.setIcon(icon);
        lblBag.setHorizontalAlignment(SwingConstants.CENTER);
        contentPane.add(lblBag);

        Random r = new Random();

        lblBag.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                boolean flag = true;
                int x = 0;
                int y = 0;
                int mx = lblBag.getX() + e.getX();
                int my = lblBag.getY() + e.getY();
                do {
                    x = r.nextInt(contentPane.getWidth() - lblBag.getWidth());
                    y = r.nextInt(contentPane.getHeight() - lblBag.getHeight());
                    int w = lblBag.getWidth();
                    int h = lblBag.getHeight();
                    flag = (mx > x) && (mx < (x + w)) && (my > y) && (my < (y + h));
                    // System.out.println(mx + " " + my);
                    // System.out.println(flag);
                } while (flag);
                lblBag.setLocation(x, y);
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                JOptionPane.showMessageDialog(null, "你抢到了红包！", "恭喜", JOptionPane.DEFAULT_OPTION);
            }
        });

        frame.setMinimumSize(new Dimension(400, 300));

        frame.setVisible(true);
    }

}